package com.rong.iconhero.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 周厚荣
 * @date 2025/4/29 15:44
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadImage(@RequestParam String imageUrl) throws Exception {
        // 打开 URL 连接
        log.error(imageUrl);
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 获取响应内容类型
        String contentType = connection.getContentType();
        if (contentType == null) {
            // 默认使用二进制流
            contentType = "application/octet-stream";
        }

        // 获取图片流
        InputStream inputStream = connection.getInputStream();

        // 设置文件名，使用图片链接中的文件名
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

        // 返回图片数据作为响应
        ResponseEntity<InputStreamResource> body = ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .header("Access-Control-Expose-Headers", "Content-Disposition")
                .contentType(MediaType.parseMediaType(contentType))
                .body(new InputStreamResource(inputStream));
        System.out.println("headers:"+body.getHeaders());
        System.out.println("body:"+body.getBody());
        return body;
    }
}
